﻿using Autofac.Core;
using IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Service;

namespace WMS.Controllers
{
    public class BiWarehouseController : Controller
    {
        /// <summary>
        /// 仓库
        /// </summary>
        private readonly IBiWarehouseService _ibws;
        /// <summary>
        /// 批次
        /// </summary>
        private readonly IWhBatchService _iwbs;
        /// <summary>
        /// 库存
        /// </summary>
        private readonly IWhInventoryService _iwis;
        /// <summary>
        /// 库位
        /// </summary>
        private readonly IWhLocationService _iwls;
       public BiWarehouseController(IBiWarehouseService ibws, IWhBatchService iwbs, IWhInventoryService iwis, IWhLocationService iwls)
        {
            _ibws = ibws;
            _iwbs = iwbs;
            _iwis = iwis;
            _iwls = iwls;
        }

        /// <summary>
        /// 主页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {

            return View();
        }
        /// <summary>
        /// 初始数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAllAsync()
        {
            var result = await _ibws.GetAllAsync();
            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "获取成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "获取失败" });
            }
        }
        /// <summary>
        /// 货品详细信息页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Details()
        {
            return View();
        }
        /// <summary>
        /// 详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Details(int id)
        {
            var result = await _ibws.GetByIdAsync(id);
            return Ok(new { code = 300, data = result, msg = "查询成功" });
        }

        /// <summary>
        /// 添加页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 添加提交
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create(BiWarehouse date)
        {
            var result = await _ibws.CreateAsync(date);
            return Ok(new { code = 200, data = result, msg = "添加成功" });
        }

        /// <summary>
        /// 修改页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Edit(int id)
        {
            return View();
        }

        /// <summary>
        /// 修改提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Edit(int id, BiWarehouse date)
        {
            var result = await _ibws.UpdateAsync(date);
            return Ok(new { code = 200, data = result, msg = "更新成功" });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            var result = await _ibws.DeleteAsync(id);
            return Ok(new { code = 200, data = result, msg = "删除成功" });
        }

        /// <summary>
        /// 两表联查
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetLocationWithManagerAsync()
        {
            try
            {
                var result = await _ibws.GetLocationWithUserAsync();
                if (result != null && result.Count > 0)
                {
                    // 有数据：返回成功+数据
                    return Ok(new
                    {
                        code = 200,
                        data = result,
                        msg = "获取成功"
                    });
                }
                else
                {
                    // 无数据：返回成功（状态码200）+ 空数据+提示
                    return Ok(new
                    {
                        code = 200,
                        data = result, // 空列表
                        msg = "查询成功，但未找到匹配数据"
                    });
                }
            }
            catch (Exception ex)
            {
                // 只有查询过程报错（如数据库连接失败），才返回失败
                return Ok(new
                {
                    code = 500,
                    msg = $"获取失败：{ex.Message}"
                });
            }
        }
        
       [HttpGet]
        public async Task<IActionResult> GetUniqueLocationManagersAsync()
        {
            try
            {
                var result = await _ibws.GetUniqueLocationManagersAsync();
                if (result != null && result.Count > 0)
                {
                    // 有数据：返回成功+数据
                    return Ok(new
                    {
                        code = 200,
                        data = result,
                        msg = "获取成功"
                    });
                }
                else
                {
                    // 无数据：返回成功（状态码200）+ 空数据+提示
                    return Ok(new
                    {
                        code = 200,
                        data = result, // 空列表
                        msg = "查询成功，但未找到匹配数据"
                    });
                }
            }
            catch (Exception ex)
            {
                // 只有查询过程报错（如数据库连接失败），才返回失败
                return Ok(new
                {
                    code = 500,
                    msg = $"获取失败：{ex.Message}"
                });
            }
        }

        [HttpPost]
        public async Task<IActionResult> LocationAddAsync(WhLocation data, long warehouseId)
        {
            // 打印接收的库位编号（调试用）
            Console.WriteLine("接收的storageLocationCode：" + data.StorageLocationCode);
            try
            {
                // 1. 先补充必填字段（关键：在调用服务层方法之前赋值）
               
                data.StorageLocationCode = data.StorageLocationCode ?? "";
                data.StorageLocationName = data.StorageLocationName ?? "";
                data.StorageLocationCapacity = data.StorageLocationCapacity;
                data.ManagerId = data.ManagerId;
                data.StorageLocationStatus = data.StorageLocationStatus;
                data.SortOrder = data.SortOrder;
                data.Remarks = data.Remarks ?? ""; // 确保Remarks不为null（空字符串）
                data.WarehouseId = warehouseId; // 补充库位关联的仓库ID（必传字段）
                var result = await _ibws.LocationAddAsync(data);
                // 若受影响行数为0，主动抛出异常（避免前端误以为成功）
                if (result == 0)
                {
                    throw new Exception("未找到可新增的库位数据，可能是字段不完整或数据无效");
                }
                return Ok(new { code = 200, data = result, msg = "添加成功" });
            }
            catch (Exception ex)
            {
                // 将错误信息返回给前端（包含具体原因）
                return StatusCode(500, new { code = 500, msg = ex.Message });
            }
        }

        [HttpPost]
        public async Task<IActionResult> CreateAsync(BiWarehouse data)
        {
            var result= await _ibws.CreateAsync(data);
            return Ok(new { code = 200, data = result, msg = "添加成功" });
        }

        //[HttpPost("SaveWithTransaction")]
        //public async Task<IActionResult> SaveWithTransaction([FromBody] WarehouseLocationViewModel model)
        //{
        //    try
        //    {
        //        // 转换视图模型到实体
        //        var warehouse = new BiWarehouse
        //        {
        //            WarehouseCode = model.Warehouse.WarehouseCode,
        //            IsDefaultWarehouse = model.Warehouse.IsDefaultWarehouse,
        //            WarehouseName = model.Warehouse.WarehouseName,
        //            WarehouseCapacity = model.Warehouse.WarehouseCapacity,
        //            ManagerId = model.Warehouse.ManagerId,
        //            ManageOrgId = model.Warehouse.ManageOrgId,
        //            UsersHoneUmber = model.Warehouse.UsersHoneUmber,
        //            WarehouseAddress = model.Warehouse.WarehouseAddress,
        //            SortOrder = model.Warehouse.SortOrder,
        //            WarehouseStatus = model.Warehouse.WarehouseStatus,
        //            WarehouseLocked = model.Warehouse.WarehouseLocked,
        //            Remarks = model.Warehouse.Remarks,
        //        };

        //        var Locations = model.Locations.Select(l => new WhLocation
        //        {
        //            StorageLocationCode = l.StorageLocationCode,
        //            StorageLocationName = l.StorageLocationName,
        //            // 其他属性映射...
        //        }).ToList();

        //        var result = await _ibws.SaveWithTransactionAsync(warehouse, Locations);
        //        return Ok(new { code = 200, msg = "保存成功", data = result });
        //    }
        //    catch (Exception ex)
        //    {
        //        return Ok(new { code = 500, msg = ex.Message });
        //    }
        //}
        // 接收仓库的"管理组织ID"，查询该部门下的用户（作为仓库主管候选）
        [HttpGet]
        public async Task<IActionResult> GetWarehouseManagers(long manageOrgId)
        {
            try
            {
                // 传入仓库表的ManageOrgId，查询匹配的用户
                var managers = await _ibws.GetWarehouseManagersAsync(manageOrgId);
                return Ok(new { code = 200, msg = "查询成功", data = managers });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = ex.Message });
            }
        }
        // 视图模型
        public class WarehouseLocationViewModel
        {
            public BiWarehouse Warehouse { get; set; }
            public List<WhLocation> Locations { get; set; }
        }
    }
}
